package com.sinosoft.vaccinetoai.security.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiazhihao
 * @ClassName: CustomModularRealmAuthenticator
 * @ClassNameExplain:
 * @Description: xiazhihao
 * @date 2025/5/31 1:35
 */

public class CustomModularRealmAuthenticator extends ModularRealmAuthenticator {


    /**
     * 动态选择登录器
     */
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {

        assertRealmsConfigured();

        Collection<Realm> realms = getRealms();

        // 过滤只支持该 token 的 Realm
        List<Realm> supportedRealms = realms.stream()
                .filter(realm -> realm.supports(authenticationToken))
                .collect(Collectors.toList());

        if (supportedRealms.isEmpty()) {
            throw new AuthenticationException("No realm supports token: " + authenticationToken.getClass());
        }

        if (supportedRealms.size() == 1) {
            return doSingleRealmAuthentication(supportedRealms.get(0), authenticationToken);
        } else {
            return doMultiRealmAuthentication(supportedRealms, authenticationToken);
        }
    }
}
